<?php


namespace App\Api\Controllers\V1\User;


use App\Api\Controllers\Controller;

class AuthController extends Controller
{
    public function login()
    {
        $credentials = request(['username', 'password']);
        if (! $token = auth('api')->attempt($credentials)) {
            return $this->error('1',[],'用户名或密码错误');
        }
        return $this->success('0',$this->respondWithToken($token),'登录成功');
    }

    public function me()
    {
        return response()->json(auth('api')->user());
    }


    public function logout()
    {
        auth('api')->logout();
        return $this->success('0',[],'退出成功');
    }

    /**
     * Refresh a token.
     * 刷新token，如果开启黑名单，以前的token便会失效。
     * 值得注意的是用上面的getToken再获取一次Token并不算做刷新，两次获得的Token是并行的，即两个都可用。
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->success('0',$this->respondWithToken(auth('api')->refresh()),'刷新成功');
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60
        ]);
    }
}
